import 'dart:async';

import 'package:flutter/material.dart';
import 'package:tiktokadult/hj_model/countdown_update_model.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';

import '../../../hj_utils/light_model.dart';
import '../../../tools_base/global_store/store.dart';

/// 我的未读消息,和新人倒计时
class MineMsgProvider with ChangeNotifier {
  static final MineMsgProvider _instance = MineMsgProvider._();
  MineMsgProvider._();
  factory MineMsgProvider() => _instance;

  static String get _alertLocalKey => "NewerVipAlert_isFirst_${GlobalStore().getMe()?.uid}"; // 弹窗只弹一次
  static Future<bool> isShowNewerAlertFirst() async{ // true: 第一次展示新人活动弹窗
    bool ret = await lightKV.getBool(_alertLocalKey, defaultValue: true) ?? true;
    MineMsgProvider().isShowNewerFloat = !ret;
    return ret;
  }

  static isShowNewerAlertFinish() async{
    MineMsgProvider().isShowNewerFloat =  true;
    await lightKV.setBool(_alertLocalKey, false);
  }
  bool isShowNewerFloat = false; // 运营那边要求:新人活动,进入过视频详情页后,先弹活动窗后,再显示新人活动浮窗


  bool visible = false; //小红点
  Countdown? countdown; //倒计时
  Timer? _time;
  bool get timeEnd => ((countdown?.leftTimeSinceEpoch ?? 0) < 1);

  int get newerTime { // 新人活动时间, 用户注册一小时内的优惠活动,超过一个小时就没有了
    int nowEpoch =  DateTime.now().millisecondsSinceEpoch~/1000;
    DateTime? userTime = DateTime.tryParse(GlobalStore().getMe()?.createdAt ?? "");
    if(userTime != null){
      int useEpoch = userTime.millisecondsSinceEpoch~/1000;
      int gapTime = nowEpoch - useEpoch;
      if(gapTime < 3600){
        return 3600 - gapTime;
      }
    }
    return -1;
  }

  String get newerTimeHour => (newerTime ~/ 3600).toString().padLeft(2, '0');

  String get newerTimeMin {
    return ((newerTime ~/ 60) % 60).toString().padLeft(2, '0');
  }

  String get newerTimeSec {
    return (newerTime % 60).toString().padLeft(2, '0');
  }

  loadData() {
    getMessageTip();
    getNewUserCountdown();
  }

  Future<void> getMessageTip() async {
    final res = await MineService.checkMessageTip();
    visible = res?.newsTip ?? false;
    notifyListeners();
  }

  //获取新人倒计时
  Future<void> getNewUserCountdown() async {
    countdown = await MineService.getCutDown();
    if (countdown != null && (countdown?.leftTimeSinceEpoch ?? 0) > 0) {
      //开启倒计时
      startTimer();
    } else {
      cancelTimer();
    }
    notifyListeners();
  }

  startTimer() {
    cancelTimer();
    _time = Timer.periodic(Duration(seconds: 1), (time) {
      notifyListeners();
      if (countdown!.leftTimeSinceEpoch < 1) {
        cancelTimer();
      }
    });
  }

  cancelTimer() {
    _time?.cancel();
    _time = null;
  }

  void readMessage() {
    visible = false;
    notifyListeners();
  }

  //红点view
  buildTipsView() {
    return visible
        ? Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              color: Color(0xfff74f49),
              borderRadius: BorderRadius.all(Radius.circular(6)),
            ),
          )
        : SizedBox.shrink();
  }
}

class NewMessageTip {
  bool? newsTip;

  NewMessageTip({this.newsTip});

  NewMessageTip.fromJson(dynamic json) {
    newsTip = json['newsTip'];
  }

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['newsTip'] = newsTip;
    return map;
  }
}
